<!-- eslint-disable vue/multi-word-component-names -->
<template >
    <div>
    <el-table
    :data="tableData"
    style="width: 100%"
    height = "700"
    empty-text="ChatGPT，基于 OpenAI 的 ChatGPT 自然语言模型人工智能对话。">
    <el-table-column prop="role" label="ROLE" width="100" />
    <el-table-column width="50" >
        <el-icon><ChatSquare /></el-icon>
    </el-table-column>
    <el-table-column prop="msg" label="Q/A" />
  </el-table>

  <el-input
    v-model="query"
    :autosize="{ minRows: 3, maxRows: 15 }"
    type="textarea"
    placeholder="输入你想问的"
    maxlength="300"
    show-word-limit
  >
  </el-input>

  <!-- <el-button @click="send" type="primary" plain style="margin-top: 10px;">发送</el-button> -->
  <div style="margin-top: 10px;">
    <el-button @click="send" type="primary" plain ><el-icon ><Position /></el-icon>  发送~</el-button>
  </div>
  

</div>
</template>
<script lang="ts" setup>
import { chat } from '@/utils/request';
import { ref } from "vue";
import { ElMessage } from 'element-plus'
interface Talk {
  role: string;
  msg: string
}
const query = ref<string>("")
const api_key = ref<string>("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")
const tableData = ref<Talk[]>([])

const send = async () => {
  if (query.value == "") {
    ElMessage.warning("请输入内容")
    return
  }
  console.log(query.value);

  console.log(tableData);

  tableData.value.push({role: "你", msg: query.value})
  tableData.value.push({role:"ChatGPT",msg:""})
  const {status, data, message} = await chat(query.value, api_key.value)
  query.value = ""
  if (status === "success" && data) {
    const reader = data.getReader();
    await readStream(reader);
  } else {
    appendLastMessageContent(message);
  }
}
const decoder = new TextDecoder("utf-8");
// eslint-disable-next-line no-undef
const readStream = async (reader: ReadableStreamDefaultReader<Uint8Array>) => {
  const { done, value } = await reader.read();
  if (done) {
    reader.closed;
    return;
  }
  const dataList = decoder.decode(value).match(/(?<=data: )\s*({.*?}]})/g);
  dataList?.forEach((v: any) => {
    const json = JSON.parse(v);
    console.log(json.choices[0].delta.content);
    
    appendLastMessageContent(json.choices[0].delta.content ?? "");
  });
  await readStream(reader);
};
const appendLastMessageContent = (content: string) =>
    (tableData.value[tableData.value.length - 1].msg += content);
</script>
